<template>
  <div class="content">
    <div class="operating">
      <div>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleCreate">添加</el-button>
        <el-button type="danger" size="small" icon="el-icon-remove-outline" @click="handleDetales">删除</el-button>
      </div>
      <div><el-button type="primary" size="small" icon="el-icon-refresh-left" @click="refresh">刷新</el-button></div>
    </div>
    <el-table v-loading="loading" :data="tags" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column label="ID" prop="id" />
      <el-table-column label="名称" prop="name">
        <template slot-scope="scope">
          <el-tag type="warning" disable-transitions>
            {{ scope.row.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column align="right" fixed="right">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            :data-id="scope.row"
            size="mini"
            placeholder="输入标签名称搜索"
            @keyup.enter.native="handleSearch"
          />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogTagForm" width="30%">
      <el-form :model="form">
        <el-form-item label="名称" label-width="20%">
          <el-input v-model="form.name" class="form-input" placeholder="请输入名称..." autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTagForm = false">取 消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="handleAddOrUpdate">保 存</el-button>
      </div>
    </el-dialog>
    <el-pagination
      v-if="page.pages"
      background
      layout="prev, pager, next"
      :current-page.sync="params.current"
      :page-size="page.size"
      :page-count="page.pages"
      @current-change="turnPage"
    />
  </div>
</template>

<script>
import { getList, deleteTag, addOrUpdate, deleteTags } from '@/api/tag'

export default {
  data() {
    return {
      search: '',
      params: {
        current: 1,
        size: 10
      },
      page: {
        current: 1,
        size: 10
      },
      loading: false,
      buttonLoading: false,
      dialogTagForm: false,
      tags: [],
      form: {
        name: ''
      },
      dialogStatus: '',
      textMap: {
        update: '修改标签',
        create: '添加标签'
      },
      selectIds: []
    }
  },
  watch: {
    'page.current': function(newCurrent) {
      this.params.current = newCurrent
    },
    'search': function(newName) {
      this.params.name = newName
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogTagForm = true
      this.form.id = null
      this.form.name = null
    },
    handleEdit(index, row) {
      this.dialogStatus = 'update'
      this.dialogTagForm = true
      if (this.form.id === null || this.form.id !== row.id) {
        this.form.id = row.id
        this.form.name = row.name
      }
    },
    handleDelete(index, row) {
      this.$confirm('是否永久删除该标签?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteTag(row.id).then(response => {
          if (response.code === 200) {
            // 删除数组里面的对象，无需再请求
            this.tags.forEach(item => {
              if (item.id === row.id) {
                this.tags.splice(this.tags.indexOf(item), 1)
                return
              }
            })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message({
              type: 'error',
              message: response.message
            })
          }
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取标签列表
    fetchData() {
      this.loading = true
      getList(this.params).then(response => {
        if (response.code === 200) {
          this.tags = response.data.records
          this.page.current = response.data.current
          this.page.size = response.data.current
          this.page.total = response.data.total
          this.page.pages = response.data.pages
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
        this.loading = false
      })
    },
    // 搜索
    handleSearch() {
      this.fetchData()
    },
    // 刷新
    refresh() {
      this.fetchData()
    },
    // 添加或修改标签
    handleAddOrUpdate() {
      this.buttonLoading = true
      addOrUpdate(this.form).then(response => {
        if (response.code === 200) {
          this.fetchData()
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '请求失败',
            message: response.message,
            type: 'error',
            duration: 2000
          })
        }
        this.buttonLoading = false
        this.dialogTagForm = false
      })
    },
    // 翻页
    turnPage() {
      this.fetchData()
    },
    // 选择复选框
    handleSelectionChange(row) {
      const selectIds = []
      if (row.length > 0) {
        row.forEach(item => {
          selectIds.push(item.id)
        })
      }
      this.selectIds = selectIds
    },
    // 删除多条
    handleDetales() {
      if (this.selectIds.length > 0) {
        const formData = new FormData()
        formData.append('ids', this.selectIds)
        deleteTags(formData).then(response => {
          if (response.code === 200) {
            this.fetchData()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '请求失败',
              message: response.message,
              type: 'error',
              duration: 2000
            })
          }
        })
      } else {
        this.$notify({
          title: '删除失败',
          message: '请选择要删除的标签',
          type: 'error',
          duration: 1500
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .el-table {
    box-shadow: 0 2px 12px 0 rgba(0,0,0, 0.1);
    border-radius: 4px;
  }

  .form-input {
    width: 80%;
  }
</style>
